import { InjectionKey } from "vue"
// import type { RuleItem, ValidateFieldsError } from 'async-validator'
import { Arrayable } from '../../utils'
import { FormProps } from './form'
import { FormItemProps } from './formItem'
// import { ValidateError } from 'async-validator'
import type { RuleItem, ValidateFieldsError, ValidateError } from '../../utils/async-validate'

/**
 * 校验规则类型
 */
 export interface FormItemRule extends RuleItem {
  trigger?: Arrayable<string>
}
export type FormRules = Partial<Record<string, Arrayable<FormItemRule>>>

/**
 * 错误信息提示类型有效值
 */
export const FormErrorTypes = ['toast', 'message', 'border', 'borderBottom', 'none'] as const
export type FormErrorType = typeof FormErrorTypes[number]
export type FormErrorTypeArray = Arrayable<FormErrorType>

/**
 * 标签显示位置有效值
 */
export const FormLabelPositions = ['top', 'left'] as const
export type FormLabelPosition = typeof FormLabelPositions[number]

/**
 * 标签对齐方式有效值
 */
export const FormLabelAligns = ['left', 'center', 'right'] as const
export type FormLabelAlign = typeof FormLabelAligns[number]

/**
 * formItem验证状态
 */
export const FormItemValidateStates = ['', 'error', 'validating', 'success'] as const
export type FormItemValidateState = typeof FormItemValidateStates[number]

/**
 * form校验回调函数类型
 */
export type FormValidateCallback = (
  isValid: boolean,
  invalidFields?: ValidateFieldsError
) => void

/**
 * form校验结果类型
 */
export type FormValidationResult = Promise<boolean>

/**
 * Form校验失败结果类型
 */
export type FormValidateFailure = {
  errors: ValidateError[] | null,
  fields: ValidateFieldsError
}

/**
 * FormContext
 */
export type FormContext = FormProps & {

  addField: (field: FormItemContext) => void,
  removeField: (field: FormItemContext) => void,
  resetFields: (props?: Arrayable<Arrayable<string>>) => void,
  clearValidate: (props?: Arrayable<Arrayable<string>>) => void,
  validateField: (
    props?: Arrayable<Arrayable<string>>,
    callback?: FormValidateCallback
  ) => FormValidationResult
}

/**
 * FormItemContext
 */
export type FormItemContext = FormItemProps & {
  $el: any,
  validateState: FormItemValidateState,
  resetField: () => void,
  clearValidate: () => void,
  validate: (
    trigger: string,
    callback?: FormValidateCallback
  ) => FormValidationResult
}

export const formContextKey: InjectionKey<FormContext> = 
  Symbol('formContextKey')
export const formItemContextKey: InjectionKey<FormItemContext> = 
  Symbol('formItemContextKey')
